package com.summer.data.dialect;

import com.summer.data.logging.Logger;
import com.summer.data.logging.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;

/**
 * @author 345480567@qq.com
 */

public class DialectCenter {

    private static final Logger logger = LoggerFactory.getLogger(DialectCenter.class);

    private static final Map<String, DialectRouter> DIALECT_ROUTER_MAP = new HashMap<String, DialectRouter>();

    static {
        ServiceLoader<DialectRouter> serviceLoader = ServiceLoader.load(DialectRouter.class);

        for (DialectRouter dialectRouter : serviceLoader) {
            String routerName = dialectRouter.getName();
            DialectRouter loadedDialectRouter = DIALECT_ROUTER_MAP.get(routerName);
            if (loadedDialectRouter == null || dialectRouter.score() > loadedDialectRouter.score()) {
                DIALECT_ROUTER_MAP.put(routerName, dialectRouter);
            }
        }
    }

    public static Dialect findDialect(String prodName, int version) {
        // 数据库产品名在内部统一吃用大写字母
        prodName = prodName.toUpperCase();

        Set<String> keySet = DIALECT_ROUTER_MAP.keySet();
        for(String key : keySet) {
            if (key.equalsIgnoreCase(prodName)) {
                DialectRouter dialectRouter = DIALECT_ROUTER_MAP.get(key);
                return dialectRouter.route(version);
            }
        }
        logger.info("没有找到 dialect: %s, %d", prodName, version);
        return null;
    }

    public static Dialect getDialect(DatabaseProductID databaseProductID) {

        DialectRouter dialectDispatch = DIALECT_ROUTER_MAP.get(databaseProductID.getProductName());
        if (dialectDispatch == null) {
            return null;
        } else {
            return dialectDispatch.route(databaseProductID.getMajorVersion());
        }

    }

    public static void regDialect(String prodName, DialectRouter dispatch) {
        prodName = prodName.toUpperCase();
        DIALECT_ROUTER_MAP.put(prodName, dispatch);
    }

}

